package com.earnings.okhttputils.utils.car.http;
import android.util.Log;

import com.earnings.okhttputils.utils.OkHttp.callback.Callback;
import com.earnings.okhttputils.utils.bean.CarBaseBean;
import com.earnings.okhttputils.utils.https.JsonGenericsSerializator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by HOHO on 2017/4/25.
 */

public abstract class GodHttpArrayCallback<T> extends Callback<String> {

    @Override
    public String parseNetworkResponse(Response response, int id) throws Exception {
        return response.body().string();
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        GodLog.Log(call.toString());
        e.printStackTrace();
        onFail(id, e.toString());
    }

    @Override
    public void onResponse(String response, int id) {
        GodLog.Log(response);
        try {
            JsonGenericsSerializator json = new JsonGenericsSerializator();
            Gson gson = new Gson();
            CarBaseBean entity = json.transform(response, CarBaseBean.class);
            //状态成功时
            if (GodHttpStatus.STATUS_SUCCESS == entity.getStatus()) {
                Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];//相当于T.class
                JsonArray jsonArray = null;
                if (entity.getData() != null) jsonArray = entity.getData().getAsJsonArray();
                Iterator it = jsonArray.iterator();
                List<T> data = new ArrayList<T>();
                while (it.hasNext()) {
                    JsonElement e = (JsonElement) it.next();
                    //JsonElement转换为JavaBean对象
                    T object;
                    if (entityClass == JSONArray.class) object = (T) new JSONArray(e.toString());
                    else if (entityClass == String.class) object = (T) (e.toString());
                    else object = gson.fromJson(e.toString(), entityClass);
                    data.add(object);
                }
                onSuccess(data, entity.getMessage(), response);

            } else {
                onFail(entity.getStatus(), entity.getMessage());
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public abstract void onSuccess(List<T> datas, String msg, String response);
    public abstract void onFail(int code, String msg);
}
